<?php

namespace app\beautiful\logic\order;



use app\beautiful\model\LevelModel;

use app\beautiful\model\mall\GoodsModel;

use app\beautiful\model\mall\GoodsSkuModel;

use app\beautiful\model\member\MemberCouponModel;

use app\beautiful\model\order\CashierOrderItemModel;

use app\beautiful\model\order\CashierOrderModel;



class OrderCashierLogic{

    use OrderTrait;

    protected $total_price=0;

    protected $member_coupon_id;

    protected $num;

    protected $is_vip=false;

    protected $order_item_data;

    protected $member_level;




    public function createOrder($params)

    {

        //判断用户

        //empty($params['member_id']) && $this->error('请先登录后再操作');

        if($params['member_id'] !=0){

            $this->checkMember($params['member_id'], false);

            //判断是不是会员

            if(null !== $this->member_level = LevelModel::where([

                    ['shop_id','=',$this->shopId],

                    ['level_id','=',$this->member->level_id],

                    ['is_delete','=',0]

                ])->find()){

                $this->is_vip=true;

            }

        }



        //判断商品

        if(empty($params['goods']) || !is_array($params))  $this->error('请选择商品');

        foreach ($params['goods'] as $k => $v){

            $this->checkGoods($v,false);

        }



        //判断总价

        if(empty($params['total_price'])) $this->error('参数错误#1');

        if((float)$params['total_price'] != $this->total_price) $this->error('参数错误#2');





        //判断优惠卷

        $coupon_id = $params['coupon_id'] ?? 0;

        $couponBalance = 0;

        if(!empty($coupon_id) && $params['member_id'] != 0){

            if(null === $myCoupon =  MemberCouponModel::find($coupon_id)) $this->error('优惠券不存在');

            if($myCoupon->status == 1 || $myCoupon->money_limit > $this->total_price) $this->error('该优惠券不可用');

            if($myCoupon->member_id != $params['member_id'])  $this->error('该优惠券不可用');

            $couponBalance = $myCoupon->coupon_money;

        }



        //获取优惠金额

        $youhui_price=$params['youhui_price'] ?? 0;



        //获取需要支付的金额

        $need_pay=round((($this->total_price)*100  - $couponBalance*100 -$youhui_price*100 )/100,2);



        //保存订单

        $order = new CashierOrderModel();

        $order_data=[

            'shop_id'=>$this->shopId,

            'member_id'=>$params['member_id'],

            'total_num'=>$this->num,

            'total_price'=>$this->total_price,

            'need_pay'=>$need_pay,

            'member_coupon_id'=>$params['coupon_id'],

            'coupon_money'=>$couponBalance,

            'youhui_price'=>$youhui_price,

            'status'=>1,

        ];

        $order->save($order_data);



        //保存订单商品

        foreach ($this->order_item_data as $k => $v){

            $this->order_item_data[$k]['order_id']=$order->order_id;

        }

        $order_item_model= new CashierOrderItemModel();

        $order_item_model->saveAll($this->order_item_data);

        return $order->order_id;

    }



    public function checkGoods($datas,$lock)

    {

        empty($datas['goods_id']) && $this->error('参数错误#3');

        empty($datas['num']) && $this->error('参数错误#4');

        $this->num = ($this->num ?? 0) + $datas['num'];



        $goods=GoodsModel::where([

            ['shop_id','=',$this->shopId],

            ['status','=',1],

            ['is_delete','=',0],

            ['goods_id','=',$datas['goods_id']]

        ])->field('goods_id,name,cover_img,original_price,vip_price,gross,quota,take_count,fictitious_take_count,
        is_have_sku,is_vip_discount')

            ->lock($lock)->find($datas['goods_id']);

        empty($goods) && $this->error('商品不存在');





        $sku_id=isset($datas['sku_id']) ? $datas['sku_id'] : 0;

        if($sku_id != 0){

            $sku=GoodsSkuModel::where([

                ['shop_id','=',$this->shopId],

                ['is_delete','=',0],

                ['goods_id','=',$datas['goods_id']],

                ['sku_id','=',$sku_id],

                ['quota','>',$datas['num']]

            ])->field('sku_id,name,original_price,vip_price,quota,take_count')

                ->lock($lock)->find();

            if(null === $sku) $this->error($goods->name.'的规格缺货');

        }else{

            if($goods['quota'] < $datas['num']) $this->error ('商品库存不足');

        }



        //处理订单商品表

        $price=isset($sku) ? ($this->is_vip ? $sku->vip_price :$sku->original_price ) : ($this->is_vip ? $goods->vip_price : $goods->original_price );

        $gross = $goods->gross;
        $pay_price = $price;

        //商品参与折扣&会员是vip，毛利及实付价格都乘以折扣
        if($goods->is_vip_discount && $this->is_vip){
            //会员的折扣率
            $discount = $this->member_level->discount;
            $pay_price = round($price * $discount / 10,2);
            $gross = round($gross * $discount / 10,2);
        }

        $this->order_item_data[]=[

            'shop_id'=>$this->shopId,

            'goods_id'=>$datas['goods_id'],

            'goods_type'=>'normal',

            'goods_name'=>$goods->name,

            'goods_gross'=>$gross,

            'goods_cover_img'=>$goods->cover_img,

            'goods_sku_id'=>$sku_id,

            'goods_sku_name'=>isset($sku) ? $sku->name : '',

            'goods_original_price'=>isset($sku) ? $sku->original_price : $goods->original_price,

            'goods_price'=>$pay_price,

            'goods_num'=>$datas['num'],

        ];

        $this->total_price=round((($this->total_price)*100+$price*$datas['num']*100)/100,2);

    }

}